const qs = require('querystring')
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer()
server.on('request', (req, res) => { 
  if (req.url === '/api/province') {
    fs.readFile(path.join(__dirname, 'data/province.json'), (err, data) => {
      if (err) return console.log(err)
      res.setHeader('Content-Type', 'application/json')
      res.end(data.toString())
    })
  } else if (req.url.startsWith('/api/city')) {
    const queryStr = req.url.split('?')[1]
    const queryObj = qs.parse(queryStr)
    fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
      if (err) return console.log(err)
      const cityObj = JSON.parse(data.toString())
      const cityList = cityObj[queryObj.pname]
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(cityList))
    })
  } else {
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('访问的资源不存在')
  }
})
server.listen(3000, () => console.log('服务器启动'))